package com.chatroom.controller;

import com.chatroom.dto.MessageDTO;
import com.chatroom.model.ChatRoom;
import com.chatroom.model.Message;
import com.chatroom.model.PrivateChatRoom;
import com.chatroom.model.User;
import com.chatroom.service.ChatRoomService;
import com.chatroom.service.MessageService;
import com.chatroom.service.PrivateChatRoomService;
import com.chatroom.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Optional;

@Controller
public class WebSocketController {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketController.class);
    private final SimpMessagingTemplate messagingTemplate;
    private final UserService userService;
    private final ChatRoomService chatRoomService;
    private final MessageService messageService;
    private final PrivateChatRoomService privateChatRoomService;

    @Autowired
    public WebSocketController(SimpMessagingTemplate messagingTemplate, UserService userService,
                              ChatRoomService chatRoomService, MessageService messageService,
                              PrivateChatRoomService privateChatRoomService) {
        this.messagingTemplate = messagingTemplate;
        this.userService = userService;
        this.chatRoomService = chatRoomService;
        this.messageService = messageService;
        this.privateChatRoomService = privateChatRoomService;
    }

    @MessageMapping("/chat.sendPrivateMessage")
    public void sendPrivateMessage(@Payload MessageDTO messageDTO) {
        logger.info("收到私聊消息: {}", messageDTO);
        
        try {
            // 如果时间戳为空，使用当前时间
            if (messageDTO.getTimestamp() == null) {
                // 本地的LocalDateTime现在需要以ISO格式字符串设置
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
                String now = LocalDateTime.now().format(formatter);
                messageDTO.setTimestamp(now);
            }
            
            Optional<User> senderOpt = userService.findByUsername(messageDTO.getSenderUsername());
            Optional<User> receiverOpt = userService.findByUsername(messageDTO.getReceiverUsername());
            
            if (senderOpt.isPresent() && receiverOpt.isPresent()) {
                User sender = senderOpt.get();
                User receiver = receiverOpt.get();
                
                logger.info("保存私聊消息. 发送者: {}, 接收者: {}", sender.getUsername(), receiver.getUsername());
                
                // 获取或创建私聊房间
                PrivateChatRoom privateChatRoom = privateChatRoomService.getOrCreatePrivateChatRoom(sender, receiver);
                
                // 保存消息
                Message savedMessage = messageService.savePrivateMessage(messageDTO.getContent(), sender, receiver);
                
                // 创建要发送的消息DTO
                MessageDTO responseDTO = new MessageDTO(savedMessage);
                responseDTO.setRoomCode(privateChatRoom.getRoomCode());  // 设置房间号
                
                // 使用主题（topic）发送，类似群聊
                String destination = "/topic/private." + privateChatRoom.getRoomCode();
                logger.info("准备发送私聊消息到主题: {}, 房间号: {}, 消息内容: {}", 
                        destination, privateChatRoom.getRoomCode(), responseDTO);
                
                // 发送消息到私聊主题
                try {
                    messagingTemplate.convertAndSend(destination, responseDTO);
                    logger.info("私聊消息已通过WebSocket发送到主题: {}", destination);
                } catch (Exception e) {
                    logger.error("WebSocket消息发送失败: {}", e.getMessage(), e);
                }
                
                logger.info("私聊消息已发送到聊天室");
            } else {
                logger.error("找不到用户. 发送者: {}, 接收者: {}", messageDTO.getSenderUsername(), messageDTO.getReceiverUsername());
            }
        } catch (Exception e) {
            logger.error("处理私聊消息时出错", e);
        }
    }

    @MessageMapping("/chat.sendGroupMessage")
    public void sendGroupMessage(@Payload MessageDTO messageDTO) {
        logger.info("收到群聊消息: {}", messageDTO);
        
        try {
            // 如果时间戳为空，使用当前时间
            if (messageDTO.getTimestamp() == null) {
                // 本地的LocalDateTime现在需要以ISO格式字符串设置
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
                String now = LocalDateTime.now().format(formatter);
                messageDTO.setTimestamp(now);
            }
            
            Optional<User> senderOpt = userService.findByUsername(messageDTO.getSenderUsername());
            Optional<ChatRoom> chatRoomOpt = chatRoomService.findByRoomCode(messageDTO.getRoomCode());
            
            if (senderOpt.isPresent() && chatRoomOpt.isPresent()) {
                User sender = senderOpt.get();
                ChatRoom chatRoom = chatRoomOpt.get();
                
                logger.info("保存群聊消息. 发送者: {}, 群聊: {}", sender.getUsername(), chatRoom.getName());
                
                Message savedMessage = messageService.saveGroupMessage(messageDTO.getContent(), sender, chatRoom);
                
                // 创建要发送的消息DTO
                MessageDTO responseDTO = new MessageDTO(savedMessage);
                logger.info("准备发送消息到群聊: {}, 目标路径: /topic/group.{}, 消息内容: {}", 
                        chatRoom.getName(), chatRoom.getRoomCode(), responseDTO);
                
                messagingTemplate.convertAndSend(
                        "/topic/group." + chatRoom.getRoomCode(),
                        responseDTO
                );
                
                logger.info("群聊消息已发送到聊天室");
            } else {
                logger.error("找不到用户或聊天室. 发送者: {}, 房间号: {}", messageDTO.getSenderUsername(), messageDTO.getRoomCode());
            }
        } catch (Exception e) {
            logger.error("处理群聊消息时出错", e);
        }
    }
} 